<?php

namespace plugin\coupon\app\admin\controller;

use app\admin\controller\Curd;
use plugin\coupon\app\admin\service\CouponService;
use plugin\coupon\app\model\Coupon;
use plugin\coupon\app\model\CouponReceiveLog;
use support\Request;

class IndexController extends Curd
{
    public function index(Request $request)
    {

        if (request()->isAjax()) {

            $couponService = new CouponService();
            $res = $couponService->getList($request->all());
            return $this->success($res);
        }
        return view('index/index');
    }

    /**
     * 添加优惠券
     */
    public function add(Request $request)
    {
        if ($request->method() === 'POST') {

            $param = $request->post();

            $couponService = new CouponService();
            $res = $couponService->addCoupon($param);
            return $this->success($res);
        }

        if (request()->isAjax()) {
            return $this->json(0,'ok',toArray((new CouponService())->getCouponGoodsList($request->input('id'))));
        }

        return view('index/add');
    }

    /**
     * 作废优惠券
     */
    public function close(Request $request)
    {
        $id = $request->input('id');

        $couponModel = new Coupon();
        $res = $couponModel->updateById([
            'status' => 2,
            'update_time' => now()
        ], $id);

        return $this->success($res);
    }

    /**
     * 领取记录
     */
    public function log(Request $request)
    {
        if (request()->isAjax()) {

            $id = $request->input('id');
            $limit = $request->input('limit');

            $couponReceiveModel = new CouponReceiveLog();
            $list = $couponReceiveModel->where('coupon_id', $id)->paginate($limit);
            return $this->json(0, 'success',returnPage($list) );
        }
    }

}